from django.db import models
from django.utils import timezone

# Create your models here.

# 标签
class Tag(models.Model):
    name = models.CharField('标签名称', max_length=64)
    create_time = models.DateTimeField('创建时间', default=timezone.now)
    last_mod_time = models.DateTimeField('修改时间', default=timezone.now)

    # 使对象在后台显示更友好，默认[<class Tag>, <>]  ['python', 'linux']
    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '标签名'   # 指定后台显示名称
        verbose_name_plural = '标签列表'   # 指定后台显示名称复数

# 分类
class Category(models.Model):
    name = models.CharField('类别名称', max_length=64)
    create_time = models.DateTimeField('创建时间', default=timezone.now)
    last_mod_time = models.DateTimeField('修改时间', default=timezone.now)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '类别'
        verbose_name_plural = '分类列表'




# 文章
class Article(models.Model):
    """ 文章表 """
    STATUS_CHOICE = (
        ('draft', '草稿'),
        ('post', '已发表'),
        ('private', '私人'),
    )

    title = models.CharField('标题', max_length=100)
    content = models.TextField('正文', blank=True, null=True)
    status = models.CharField('状态', max_length=10, choices=STATUS_CHOICE, default=STATUS_CHOICE[0][0])
    views = models.PositiveIntegerField('浏览量', default=0)

    create_time = models.DateTimeField('创建时间', default=timezone.now)
    pub_time = models.DateTimeField('发布时间', blank=True, null=True)
    last_mod_time = models.DateTimeField('修改时间', default=timezone.now)

    # article表category_id字段存储category表id字段的值。
    # 多对多关系时生成article_tag_mapping(id, article_id, tag_id)表
    # 根据article.id查出所有的对应tag。
    # 外键
    category = models.ForeignKey(Category, verbose_name='分类id', on_delete=models.CASCADE, blank=False, null=False)
    tags = models.ManyToManyField(Tag, verbose_name='标签集合', blank=True)

    def __str__(self):
        return self.title

    def viewed(self):
        self.views += 1
        self.save(update_fields=['views'])

    # 下一篇
    def next_article(self):
        # id比当前id大，状态为已发布，发布时间不为空
        return Article.objects.filter(id__gt=self.id, status='post', pub_time__isnull=False).first()

    # 前一篇
    def prev_article(self):
        # id比当前id小，状态为已发布，发布时间不为空
        return Article.objects.filter(id__lt=self.id, status='post', pub_time__isnull=False).first()

    class Meta:
        ordering = ['-pub_time']  # 按文章创建日期降序
        verbose_name = '文章'
        verbose_name_plural = '文章列表'
        get_latest_by = 'create_time'